package com.arnold.learn.impala;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.*;
import java.util.ResourceBundle;

/**
 * Created by arnold.zhu on 2017/7/27.
 */
public class ImpalaUtil {

    private static Logger logger = LoggerFactory.getLogger(ImpalaUtil.class);

    private static ResourceBundle rb = ResourceBundle.getBundle("couchbase");
    private static String url = rb.getString("impala.url");
    private static String driver = rb.getString("impala.driver");

    static {
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建连接
     *
     * @return Connection
     */
    public static Connection createConnection() {
        Connection conn = null;
        try {
            long start = System.currentTimeMillis();
            logger.info("------------>开始获取连接..");
            conn = DriverManager.getConnection(url);
            long end = System.currentTimeMillis() - start;
            logger.info("------------>获取连接的时间:" + end);
        } catch (SQLException e) {
            logger.error("Error occured when createConnection...");
            e.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        logger.info("------------>获取连接成功..");
        return conn;

    }

    public static ResultSet getQueryResult(Connection connection, String query) {
        ResultSet resultSet = null;
        try {
            Statement statement = connection.createStatement();
            resultSet = statement.executeQuery(query);
        } catch (SQLException e) {
            logger.error("Error occured when getQueryResult...");
            e.printStackTrace();
        }
        return resultSet;
    }

    public static void closeResultSet(ResultSet rs) {
        try {
            rs.close();
        } catch (SQLException e) {
            logger.error("Error occured when closeResultSet...");
            e.printStackTrace();
        }
    }

    public static void closeConnection(Connection connection) {
        try {
            connection.close();
        } catch (SQLException e) {
            logger.error("Error occured when closeConnection...");
            e.printStackTrace();
        }
    }

}
